package cc.booku.owlbox.VideoPlayer;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dueeeke.videocontroller.StandardVideoController;
import com.dueeeke.videoplayer.listener.OnVideoViewStateChangeListener;
import com.dueeeke.videoplayer.player.IjkVideoView;
import com.dueeeke.videoplayer.util.L;
import com.sunfusheng.marqueeview.MarqueeView;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import cc.booku.owlbox.ArtDesign.SystemUtil;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.R;
import cc.booku.owlbox.RsaUtil.Decrypt;
import cc.booku.owlbox.loadSqlite.DatabaseHelper;
import jaygoo.library.m3u8downloader.M3U8Downloader;
import jaygoo.library.m3u8downloader.M3U8DownloaderConfig;
import jaygoo.library.m3u8downloader.OnM3U8DownloadListener;
import jaygoo.library.m3u8downloader.bean.M3U8Task;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class VideoPlayerActivity extends AppCompatActivity implements ObservableScrollView.ScrollViewListener {
    private Toolbar Toolbar;
    private TextView Tv_videoinform, Tv_synopsis, topPanel, tv_changebatch, tv_discuss, love_collect, tv_skip;
    private MarqueeView Tv_label;
    private NetworkImageView Image_cover;
    private NoScrollGridView tvseries_list;
    private WebView webView;
    /**
     * 视频全屏参数
     */
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;
    private FrameLayout fullscreenContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;
    private List<TVSeries_C> tvSeries_cList = new ArrayList<TVSeries_C>();
    private String ProfilePath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + "Profile.txt";
    private String filePath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + "UserData" + File.separator;
    private String filedown = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + "UserData" + File.separator + "VideoDownload.txt";
    private ObservableScrollView scrollView;
    //private View middlePanel;
    private int topHeight;
    private NoScrollGridView lv_related;
    private List<Related_C> related_cList = new ArrayList<Related_C>();
    private String dirPath;
    private ImageView player_module_download, player_module_x2, player_module_collect;

    private TextView down_info, ic_x2;
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };
    M3U8Task[] taskList = new M3U8Task[1];
    private IjkVideoView ijkVideoView;
    private ProgressBarView progressBarView;

    public String tv_series = null;
    public String tv_url = null;
    private List<player_discuss_class> player_discuss_classList = new ArrayList<player_discuss_class>();
    private TDialog tDialog;
    private GridView player_discuss_list;

    private SQLiteDatabase db;
    private DatabaseHelper helper;
    private Button bt_qq;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_player);

        initsqlite();
        //加载标题栏
        LoadToolbar();
        //状态栏颜色
        SystemUtil.setStatusBarColor(this, Color.parseColor("#448aca"));
        ijkVideoView = findViewById(R.id.player);
        player_discuss_list = (GridView) findViewById(R.id.player_discuss_list);
        tv_skip = (TextView) findViewById(R.id.tv_skip);
        tvSkipGone();
        Image_cover = (NetworkImageView) findViewById(R.id.image_cover);
        Tv_videoinform = (TextView) findViewById(R.id.tv_videoinform);
        Tv_synopsis = (TextView) findViewById(R.id.tv_synopsis);
        love_collect = (TextView) findViewById(R.id.love_collect);
        down_info = (TextView) findViewById(R.id.down_info);
        tv_discuss = (TextView) findViewById(R.id.tv_discuss);

        webView = (WebView) findViewById(R.id.webvideo);
        tvseries_list = (NoScrollGridView) findViewById(R.id.tvseries_list);
        scrollView = (ObservableScrollView) findViewById(R.id.scrollView);
        lv_related = (NoScrollGridView) findViewById(R.id.lv_related);
        //middlePanel =findViewById(R.id.middlePanel);
        Tv_label = (MarqueeView) findViewById(R.id.tv_label);

        bt_qq = (Button) findViewById(R.id.bt_qq);
        tv_changebatch = (TextView) findViewById(R.id.tv_changebatch);
        down_info = (TextView) findViewById(R.id.down_info);
        progressBarView = (ProgressBarView) findViewById(R.id.progress_bar_view);
        player_module_download = (ImageView) findViewById(R.id.player_module_download);
        topPanel = (TextView) findViewById(R.id.topPanel);
        ic_x2 = (TextView) findViewById(R.id.ic_x2);
        player_module_collect = (ImageView) findViewById(R.id.player_module_collect);
        player_module_x2 = (ImageView) findViewById(R.id.player_module_x2);
        initControl();


        Bundle bundle = getIntent().getExtras();
        String vod_pic = bundle.getString("vod_pic");

        //下面的这个方法必须在子线程中执行

        funlove_init();

        fundown_init();

        // funhistory_init();
        funhistory();//是否添加历史记录

        String BillBoard_V = FileoOperations.readAssetsTxt(VideoPlayerActivity.this, "TxtData/BillBoard");
        JSONObject objsd = JSONObject.parseObject(BillBoard_V);
        String result1 = objsd.getString("公告1");
        String result2 = objsd.getString("公告2");
        String result3 = objsd.getString("公告3");
        String result4 = objsd.getString("公告4");
        List<String> messages = new ArrayList<>();
        messages.add(result1);
        messages.add(result2);
        messages.add(result3);
        messages.add(result4);
        //  Tv_label.startWithList(messages);
// 在代码里设置自己的动画
        Tv_label.startWithList(messages, R.anim.anim_bottom_in, R.anim.anim_top_out);


        //新页面接收数据
        ReceiveData();


        //读取文件
        String ProfileStr = FileoOperations.readFromSDFile(this, ProfilePath);
        //读取配置文件信息
        try {
            JSONObject obj = JSONObject.parseObject(ProfileStr);
            String result = obj.getString("默认播放器");
            if (result.equals("ijk")) {
                ijkVideoView.setVisibility(View.VISIBLE);
                webView.setVisibility(View.GONE);

                //Bundle bundle = getIntent().getExtras();
                String vod_name = bundle.getString("vod_name");
                String vod_play_url = bundle.getString("vod_play_url");

                //如果存在$就使用$分割
                if (vod_play_url.indexOf("$") != -1) {
//Log.d(vod_play_url, "---###---" + vod_play_url);
                    if (vod_play_url.indexOf("#") != -1) {

                        Log.d(vod_play_url, "---###---" + "应该是个剧集");
                    } else {
                        String[] str1 = vod_play_url.split("\\$");//拆分需要加正则，查看是否存在不需要

                        init_ijkplayer(str1[1], vod_name);
                    }
                }//否则直接传给webview
                else {
                    init_ijkplayer(vod_play_url, vod_name);
                }


            } else if (result.equals("web")) {
                ijkVideoView.setVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
                //初始化视频

                //Bundle bundle = getIntent().getExtras();
                String vod_name = bundle.getString("vod_name");
                String vod_play_url = bundle.getString("vod_play_url");

                //如果存在$就使用$分割
                if (vod_play_url.indexOf("$") != -1) {
//Log.d(vod_play_url, "---###---" + vod_play_url);
                    if (vod_play_url.indexOf("#") != -1) {

                        Log.d(vod_play_url, "---###---" + "应该是个剧集");
                    } else {
                        String[] str1 = vod_play_url.split("\\$");//拆分需要加正则，查看是否存在不需要

                        initWebView(str1[1]);
                    }
                }//否则直接传给webview
                else {
                    initWebView(vod_play_url);
                }


                //initWebView(str1[1]);
            }
        } catch (Exception e) {

            Toast.makeText(VideoPlayerActivity.this, "播放器为ijk/web", Toast.LENGTH_SHORT).show();
//异常处理
        }


        //读取密文
        JSONObject obj = JSONObject.parseObject(ProfileStr);
        String ciphertext = obj.getString("地址密文");
        String res = Decrypt.RsaDecrypt(VideoPlayerActivity.this, ciphertext);
        String result = obj.getString("评论列表");
        //Bundle bundle = getIntent().getExtras();
        String vod_class = bundle.getString("vod_class");
        String[] labelDate = vod_class.split("\\#");//影片id
        //初始化列表
        init_episode();
        //初始化评论
        // res+result+labelDate[4]
        Log.i("response===========>", "http://192.168.1.102:2020/TV/cinema/comment.php?comment_rid=22");

        try {

            // if(checkUrl(res + result + labelDate[4],400)){
            init_discuss_data(res + result + labelDate[4]);
            // }else Log.i("response===========>", res + result + labelDate[4]);

        } catch (Exception e) {

            Log.i("response===========>", res + result + labelDate[4]);
//异常处理
        }


//        //加载相关数据
//        Bundle bundle = getIntent().getExtras();
//        String vod_class = bundle.getString("vod_class");
        Message msg = new Message();
        msg.what = 12;
        bundle = new Bundle();
        bundle.putString("SearchData", vod_class);  //往Bundle中存放数据
        msg.setData(bundle);//mes利用Bundle传递数据
        handler.sendMessage(msg);//用activity中的handler发送消息

        scrollView.setScrollViewListener(this);
        //播放状态监听
        ijkVideoView.addOnVideoViewStateChangeListener(mOnVideoViewStateChangeListener);


    }


    //控件按钮
    private void initControl() {

        Image_cover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = getIntent().getExtras();
                String vod_pic = bundle.getString("vod_pic");
                Log.d("**********", "-----" + vod_pic);
                ImageDialog(vod_pic);
            }
        });

        tv_skip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long pos = ijkVideoView.getCurrentPosition();
                pos = 120000; // milliseconds
                ijkVideoView.seekTo(pos);
                setProgress(1000);
                tv_skip.setVisibility(View.GONE);
                // Toast.makeText(PlayerActivity.this, "快退05秒", Toast.LENGTH_SHORT).show();
            }
        });

        tv_discuss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                new TDialog.Builder(getSupportFragmentManager())
                        .setLayoutRes(R.layout.tdialog_evaluate)
                        .setScreenWidthAspect(VideoPlayerActivity.this, 1.0f)
                        .setGravity(Gravity.BOTTOM)
                        .addOnClickListener(R.id.btn_evluate)
                        .setOnViewClickListener(new OnViewClickListener() {
                            @Override
                            public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                                //EditText editText = viewHolder.getView(R.id.editText);
                                EditText editText = viewHolder.getView(R.id.editText);
                                String content = editText.getText().toString().trim();

                                //读取文件
                                String ProfileStr = FileoOperations.readFromSDFile(VideoPlayerActivity.this, ProfilePath);

                                JSONObject obj = JSONObject.parseObject(ProfileStr);
                                String ciphertext = obj.getString("地址密文");
                                String result = obj.getString("发表评论");
                                String resultlist = obj.getString("评论列表");
                                String res = Decrypt.RsaDecrypt(VideoPlayerActivity.this, ciphertext);

                                String user_id = "1";
                                String comment_name = "匿名";
                                //player_discuss_editid.getText().toString();//评论信息
                                Bundle bundle = getIntent().getExtras();
                                String vod_class = bundle.getString("vod_class");
                                String[] labelDate = vod_class.split("\\#");//影片id

                                Log.d("++++++++++++", labelDate[3] + "---" + labelDate[4]);

                                String url = res + result + "comment_rid=" + labelDate[4] + "&user_id=" + user_id + "&comment_name=" + comment_name + "&comment_content=" + content + "";


                                try {

                                    // if(checkUrl(url,400)){
                                    //请求，将数据写入
                                    HttpADDdiscuss(url, null);
                                    // }else Log.i("response===========>", url);

                                } catch (Exception e) {

                                    Log.i("response===========>", url);
//异常处理
                                }


                                //调用loop刷新
                                //initDiscussList();

                                // //初始化列表
                                // init_episode();
                                // Log.d("初始化评论列表", "初始化评论列表");
                                // //初始化评论
                                // init_discuss_data(res+result);
                                // Log.d("初始化评论", res+result);

                                //发布完成后，刷新
                                player_discuss_classList.clear();
                                Log.d(String.valueOf(player_discuss_classList), "发布完成后，刷新");

                                //初始化评论
                                //res+result+labelDate[4]
                                //Log.i("response===========>","http://192.168.1.102:2020/TV/cinema/comment.php?comment_rid=22");

                                // if(checkUrl(res + resultlist + labelDate[4],400)){
                                init_discuss_data(res + resultlist + labelDate[4]);
                                // }else Log.i("response===========>", res + result + labelDate[4]);


                                //初始化列表
                                //init_episode();
                                //初始化评论
                                // init_discuss_data(res+result);

                                tDialog.dismiss();
                            }
                        })
                        .create()
                        .show();


            }
        });

        bt_qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    SystemUtil.joinQQGroup(VideoPlayerActivity.this, "WZXjv7I736JKIJ48YTlIfCuLvHlWTx0a");
                } catch (Exception e) {
                    //异常处理
                    bt_qq.setText("打开失败！点击重试~");
                }
            }
        });
        tv_changebatch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                related_cList.clear();
                //加载相关数据
                Bundle bundle = getIntent().getExtras();
                String vod_class = bundle.getString("vod_class");
                Message msg = new Message();
                msg.what = 12;
                bundle = new Bundle();
                bundle.putString("SearchData", vod_class);  //往Bundle中存放数据
                msg.setData(bundle);//mes利用Bundle传递数据
                handler.sendMessage(msg);//用activity中的handler发送消息
            }
        });

        player_module_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (progressBarView.getVisibility() == View.VISIBLE) {
                    progressBarView.setVisibility(View.GONE);

                } else if (progressBarView.getVisibility() == View.GONE) {
                    progressBarView.setVisibility(View.VISIBLE);
                }

                onDownload();
            }
        });
        topPanel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                scrollView.scrollTo(0, 0);


            }
        });
        player_module_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Toast.makeText(VideoPlayerActivity.this, "待开发", Toast.LENGTH_SHORT).show();
                //新页面接收数据
                Bundle bundle = getIntent().getExtras();
                String vod_class = bundle.getString("vod_class");
                String vod_score = bundle.getString("vod_score");
                String vod_name = bundle.getString("vod_name");
                String vod_add_time = bundle.getString("vod_add_time");
                String vod_play_url = bundle.getString("vod_play_url");
                String vod_pic = bundle.getString("vod_pic");
                String vod_value_add = bundle.getString("vod_value_add");

                if (love_collect.getText().toString().equals("已收藏")) {

                    db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
                    db.delete("loveTable", "vod_name=?", new String[]{vod_name});

                    db.close();

                    love_collect.setText("已取消");
                } else {


                    db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
                    //使用 ContentValues 来对要添加的数据进行组装
                    ContentValues valuec = new ContentValues();
                    // 开始组装第一条数据
                    valuec.put("vod_score", vod_score);
                    valuec.put("vod_name", vod_name);
                    valuec.put("vod_class", vod_class);
                    valuec.put("vod_pic", vod_pic);
                    valuec.put("vod_play_url", vod_play_url);
                    valuec.put("vod_add_time", vod_add_time);
                    valuec.put("vod_value_add", vod_value_add);
                    // 插入第一条数据love_
                    db.insert("loveTable", null, valuec);
                    valuec.clear();
                    db.close();

                    love_collect.setText("已收藏");


                }


            }
        });


        player_module_x2.setOnClickListener(new View.OnClickListener() {
            int count = 1;
            int click = count;

            @Override
            public void onClick(View v) {

                switch (click) {
                    case 1:
                        ijkVideoView.setSpeed(0.5f);
                        click++;
                        ic_x2.setText("0.5f");
                        break;
                    case 2:
                        ijkVideoView.setSpeed(0.75f);
                        click++;
                        ic_x2.setText("0.75f");
                        break;
                    case 3:
                        ijkVideoView.setSpeed(1.0f);
                        click++;
                        ic_x2.setText("1.0f");
                        break;
                    case 4:
                        ijkVideoView.setSpeed(1.5f);
                        click++;
                        ic_x2.setText("1.5f");
                        break;
                    case 5:
                        ijkVideoView.setSpeed(2.0f);
                        click = count;
                        ic_x2.setText("2.0f");
                        break;
                }

            }
        });


    }

    //等待刷新函数
    private void tvSkipGone() {
        //Toast.makeText(PlayerActivity.this, "编辑成功", Toast.LENGTH_SHORT).show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //finish();
                //AnimationUtils.showAndHiddenAnimation(tv_skip, AnimationUtils.AnimationState.STATE_HIDDEN,2000);
                tv_skip.setVisibility(View.GONE);
            }
        }, 20000);
        // onCreate(null);//调用此方法刷新页面

    }

    public void initsqlite() {
        //5.实例化SQLiteOpenHelper的子类对象-MyDataBaseHelper
        helper = new DatabaseHelper(this, "dbdate", null, R.string.db_version);//dbName数据库名
        db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
    }


    public static Boolean checkUrl(String address, int waitMilliSecond) {
        try {
            URL url = new URL(address);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setConnectTimeout(waitMilliSecond);
            conn.setReadTimeout(waitMilliSecond);

            //HTTP connect
            try {
                conn.connect();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

            int code = conn.getResponseCode();
            if ((code >= 100) && (code < 400)) {
                return true;
            }

            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    private void HttpADDdiscuss(String url, final TextView textView) {


        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String res = response.body().string();
                //Log.i("response===========>",res);
                if (textView == null) {
                    Log.i("response===========>", res);

                } else {
                    textView.setText(res);
                }

            }
        });

    }


    @Override
    protected void onStop() {
        super.onStop();
        webView.reload();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        Rect frame = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;//状态栏高度

        int titleBarHeight = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();//标题栏高度
        topHeight = titleBarHeight + statusBarHeight;
    }


    public void init_ijkplayer(String URL, String title) {


        StandardVideoController controller = new StandardVideoController(this);
        //String title = intent.getStringExtra(IntentKeys.TITLE);
        controller.setTitle(title);
        //intent.getStringExtra("url")
        ijkVideoView.setUrl(URL);
        ijkVideoView.setVideoController(controller);
        ijkVideoView.release();

    }


    private void LoadToolbar() {
        //新页面接收数据
        Toolbar = (Toolbar) findViewById(R.id.toolbar);
//        Toolbar.inflateMenu(R.menu.menu_user);
        //设置的点击事件
        //设置标题名称
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        String vod_name = bundle.getString("vod_name");
        Toolbar.setTitle(vod_name);

        setSupportActionBar(Toolbar);//利用Toolbar代替ActionBar
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到用户设置页面
                finish();
            }
        });
        //添加menu 菜单点击事件
        Toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_share:

                        Bundle bundle = getIntent().getExtras();
                        final String vod_name = bundle.getString("vod_name");
                        final String vod_play_url = bundle.getString("vod_play_url");
                        final String vod_pic = bundle.getString("vod_pic");
                        Intent textIntent = new Intent(Intent.ACTION_SEND);
                        textIntent.setType("text/plain");
                        textIntent.putExtra(Intent.EXTRA_TEXT, "《" + vod_name + "》" + "\n视频地址：" + vod_play_url);
                        startActivity(Intent.createChooser(textIntent, "绿色分享，不含推广内容"));
                        break;

                }
                return true;
            }
        });
    }


    @Override
    public boolean onCreatePanelMenu(int featureId, Menu menu) {
        getMenuInflater().inflate(R.menu.menu_share, menu);//toolbar添加menu菜单
        return true;
    }


    private void ReceiveData() {

        //新页面接收数据
        Bundle bundle = getIntent().getExtras();
//        String vod_class = bundle.getString("vod_class");
//        String vod_score = bundle.getString("vod_score");
//        String vod_name = bundle.getString("vod_name");
//        String vod_add_time = bundle.getString("vod_add_time");
//        String vod_play_url = bundle.getString("vod_play_url");
        String vod_pic = bundle.getString("vod_pic");
        String vod_value_add = bundle.getString("vod_value_add");

        String[] str1 = vod_value_add.split("\\$");
        Tv_videoinform.setText(str1[0]);
        Tv_synopsis.setText(str1[1]);
        Image_cover.setImageURL(vod_pic);

    }


    /**
     * 展示网页界面
     **/
    public void initWebView(String vod_play_url) {
        WebChromeClient wvcc = new WebChromeClient();
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true); // 关键点
        webSettings.setAllowFileAccess(true); // 允许访问文件
        webSettings.setSupportZoom(true); // 支持缩放
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); // 不加载缓存内容

        webView.setWebChromeClient(wvcc);
        WebViewClient wvc = new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                webView.loadUrl(url);
                return true;
            }
        };
        webView.setWebViewClient(wvc);

        webView.setWebChromeClient(new WebChromeClient() {

            /*** 视频播放相关的方法 **/

            @Override
            public View getVideoLoadingProgressView() {
                FrameLayout frameLayout = new FrameLayout(VideoPlayerActivity.this);
                frameLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
                return frameLayout;
            }

            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                showCustomView(view, callback);
            }

            @Override
            public void onHideCustomView() {
                hideCustomView();
            }
        });

//        Bundle bundle = this.getIntent().getExtras();
//        //接收name值
//        String vod_play_url = bundle.getString("vod_play_url");

        //如果存在$就使用$分割
        if (vod_play_url.indexOf("$") != -1) {
//Log.d(vod_play_url, "---###---" + vod_play_url);
            if (vod_play_url.indexOf("#") != -1) {

                //Log.d(vod_play_url, "---###---" + "应该是个剧集");
                //Toast.makeText(VideoPlayerActivity.this, "选择剧集开始播放", Toast.LENGTH_SHORT).show();

                String PlayerURL[] = vod_play_url.split("#");
                String PlayerURL2[] = PlayerURL[0].split("\\$");
                webView.loadUrl(SD_analysisport() + PlayerURL2[1]);
            } else {
                String[] str1 = vod_play_url.split("\\$");//拆分需要加正则，查看是否存在不需要

                //读取DefaultPort.txt
                // String DefaultPort = FileoOperations.readFromSDFile(VideoPlayerActivity.this, "/storage/emulated/0/OwlDatabase/DefaultPort.txt");
                // Log.d("**********", "-----" + DefaultPort + str1[1]);
                // 加载Web地址
                webView.loadUrl(SD_analysisport() + vod_play_url);
            }
        }//否则直接传给webview
        else {
            webView.loadUrl(vod_play_url);
        }

    }

    private String SD_analysisport() {

        //读取sd文件的json
        String ProfileStr = FileoOperations.readFromSDFile(this, ProfilePath);
        //读取配置文件信息
        try {
            JSONObject obj = JSONObject.parseObject(ProfileStr);
            String result = obj.getString("默认解析口");
            return result;
        } catch (Exception e) {

            Toast.makeText(VideoPlayerActivity.this, "配置文件错误", Toast.LENGTH_SHORT).show();
//异常处理
        }

        return null;
    }


    /**
     * 视频播放全屏
     **/
    private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

        VideoPlayerActivity.this.getWindow().getDecorView();

        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        fullscreenContainer = new VideoPlayerActivity.FullscreenHolder(VideoPlayerActivity.this);
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
    }

    /**
     * 隐藏视频全屏
     */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        setStatusBarVisibility(true);
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        webView.setVisibility(View.VISIBLE);
    }

    /**
     * 全屏容器界面
     */
    static class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }
    }

    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                /** 回退键 事件处理 优先级:视频播放全屏-网页回退-关闭页面 */
                if (customView != null) {
                    hideCustomView();
                } else if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
                return true;
            default:
                return super.onKeyUp(keyCode, event);
        }
    }


    private TVSeries_A tvSeriesA;

    private void CollectData(ArrayList<TVSeries_C> tvSeries_cList) {

        tvSeriesA = new TVSeries_A(R.layout.tvseries_item, this, tvSeries_cList);

        tvseries_list.setAdapter(tvSeriesA);
        tvseries_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                TextView tv_series = (TextView) view.findViewById(R.id.tv_series);//电影名称
                TextView tv_url = (TextView) view.findViewById(R.id.tv_url);//类型

                String tv_series1 = tv_series.getText().toString();
                //gather_url1 = null;
                String tv_url1 = tv_url.getText().toString();
                tv_series.setTextColor(Color.parseColor("#00C5CD"));


                // TODO Auto-generated method stub
                Message msg = new Message();
                msg.what = 15;
                Bundle bundle = new Bundle();
                bundle.putString("videourl", tv_url1);
                bundle.putString("episodetitle", tv_series1);
                msg.setData(bundle);
                episodehandler.sendMessage(msg);
//
//                Log.i("test======", "===gather_name1===" + tv_series1 + "===gather_url1===" + tv_url1);


            }
        });

    }

    private TVSeries_C tvSeries_c;

    public void url_split(final String full_url) {


        //搜索是否存在# 存在就遍历
        //不存在就安按照$取数

        //拆分 full_url = purl

        boolean status = full_url.contains("#");
        if (status) {


            System.out.println("存在");
            //做成json
            String full_url1 = "[{" + "\"TVSeries\":\"" + full_url + "\"}]";
            String full_url2 = full_url1.replace("#", "\"},{\"TVSeries\":\"");
            String full_url3 = full_url2.replace("$", "\",\"TVUrl\":\"");
            //JSONObject json = JSONObject.fromObject(str)

            System.out.println(full_url3);//已经显示出来了

            ByteArrayInputStream stream = new ByteArrayInputStream(full_url3.getBytes());
            StringBuffer stringBuffer = new StringBuffer();
            String str = null;
            BufferedReader br = new BufferedReader(new InputStreamReader(stream));
            try {
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //03.使用fastJson解析Json、
            List<TVSeries_C> gatherc = JSON.parseArray(stringBuffer.toString(), TVSeries_C.class);
            for (TVSeries_C pp : gatherc) {
                tvSeries_c = new TVSeries_C();
                String tvUrl = pp.getTVUrl();
                String tvSeries = pp.getTVSeries();

                tvSeries_c.setTVUrl(tvUrl);
                tvSeries_c.setTVSeries(tvSeries);

                //pfilmclass.setParea(carea);
                //将结果添加到对象集合中
                tvSeries_cList.add(tvSeries_c);
            }
            Message msg = new Message();
            msg.what = 9;
            episodehandler.sendMessage(msg);//用activity中的handler发送消息

        } else {
            System.out.println("不存在");
            //不存在就 按照$拆分成数组，第一[0]就写到控件[1]写到链接
            //Toast.makeText(this, "该影片无其他剧集", Toast.LENGTH_SHORT).show();
            String full_url1 = "[{" + "\"TVSeries\":\"" + full_url + "\"}]";
            String full_url3 = full_url1.replace("$", "\",\"TVUrl\":\"");
            //JSONObject json = JSONObject.fromObject(str)

            System.out.println(full_url3);//已经显示出来了

            ByteArrayInputStream stream = new ByteArrayInputStream(full_url3.getBytes());
            StringBuffer stringBuffer = new StringBuffer();
            String str = null;
            BufferedReader br = new BufferedReader(new InputStreamReader(stream));
            try {
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //03.使用fastJson解析Json、
            List<TVSeries_C> gatherc = JSON.parseArray(stringBuffer.toString(), TVSeries_C.class);
            for (TVSeries_C pp : gatherc) {
                tvSeries_c = new TVSeries_C();
                String tvUrl = pp.getTVUrl();
                String tvSeries = pp.getTVSeries();

                tvSeries_c.setTVUrl(tvUrl);
                tvSeries_c.setTVSeries(tvSeries);

                //pfilmclass.setParea(carea);
                //将结果添加到对象集合中
                tvSeries_cList.add(tvSeries_c);
            }
            Message msg = new Message();
            msg.what = 9;
            episodehandler.sendMessage(msg);//用activity中的handler发送消息


        }

    }

    private Handler episodehandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case 5:

                    String vod_play_url5 = msg.getData().getString("vod_play_url");

                    url_split(vod_play_url5);
                    break;

                case 9:

                    CollectData((ArrayList<TVSeries_C>) tvSeries_cList);

                    break;

                case 15:
                    Bundle bundle = getIntent().getExtras();
                    String vod_name = bundle.getString("vod_name");
                    // String episodetitle = bundle.getString("episodetitle");
                    tv_url = msg.getData().getString("videourl");//接受msg传递过来的参数
                    tv_series = msg.getData().getString("episodetitle");//接受msg传递过来的参数

                    //String episodetitle = msg.getData().getString("episodetitle");
                    //String parsedUrl = P2pEngine.getInstance().parseStreamUrl(videourl);
                    //mediaPlayer.play(parsedUrl);
                    Toolbar.setTitle(tv_series + "-" + vod_name);


                    //判断哪个没有隐藏

                    String ProfileStr = FileoOperations.readFromSDFile(VideoPlayerActivity.this, ProfilePath);
                    //读取配置文件信息
                    try {
                        JSONObject obj = JSONObject.parseObject(ProfileStr);
                        String result = obj.getString("默认播放器");
                        if (result.equals("ijk")) {
                            init_ijkplayer(tv_url, vod_name + "-" + tv_series);

                            tv_skip.setVisibility(View.VISIBLE);
                            tvSkipGone();
                        } else if (result.equals("web")) {
                            initWebView(tv_url);
                        }
                    } catch (Exception e) {

                        Toast.makeText(VideoPlayerActivity.this, "播放器为ijk/web", Toast.LENGTH_SHORT).show();
//异常处理
                    }


                    break;

                case 25:
                    int locationY = msg.getData().getInt("locationY");
                    int topHeight = msg.getData().getInt("topHeight");

                    if (locationY <= topHeight && (topPanel.getVisibility() == View.GONE || topPanel.getVisibility() == View.INVISIBLE)) {
                        topPanel.setVisibility(View.VISIBLE);
                    }

                    if (locationY > topHeight && topPanel.getVisibility() == View.VISIBLE) {
                        topPanel.setVisibility(View.GONE);
                    }
                    break;
            }
        }
    };

    private void init_episode() {

        Bundle bundle = getIntent().getExtras();
        String vod_play_url = bundle.getString("vod_play_url");


        Message msg = new Message();
        msg.what = 5;
        bundle = new Bundle();
        bundle.putString("vod_play_url", vod_play_url);  //往Bundle中存放数据
        msg.setData(bundle);//mes利用Bundle传递数据
        episodehandler.sendMessage(msg);//用activity中的handler发送消息
    }


    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        int[] location = new int[2];
        Tv_label.getLocationOnScreen(location);
        int locationY = location[1];
        //Log.e("locationY", locationY + "   " + "topHeight的值是：" + topHeight);

        if (locationY <= topHeight && (topPanel.getVisibility() == View.GONE || topPanel.getVisibility() == View.INVISIBLE)) {
            topPanel.setVisibility(View.VISIBLE);
        }

        if (locationY > topHeight && topPanel.getVisibility() == View.VISIBLE) {
            topPanel.setVisibility(View.GONE);
        }
//        Message msg = new Message();
//        msg.what = 25;
//        Bundle bundle = new Bundle();
//        bundle.putInt("locationY", locationY);  //往Bundle中存放数据
//        bundle.putInt("topHeight", topHeight);  //往Bundle中存放数据
//        msg.setData(bundle);//mes利用Bundle传递数据
//        episodehandler.sendMessage(msg);//用activity中的handler发送消息


    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case 12:

                    String ProfileStr = FileoOperations.readFromSDFile(VideoPlayerActivity.this, ProfilePath);
                    //读取配置文件信息
                    try {
                        JSONObject obj = JSONObject.parseObject(ProfileStr);
                        String trfl = obj.getString("加密敏感资源");


                        String result = obj.getString("类型相关视频");

                        String str9 = msg.getData().getString("SearchData");//接受msg传递过来的参数

                        String ciphertext = obj.getString("地址密文");
                        String res = Decrypt.RsaDecrypt(VideoPlayerActivity.this, ciphertext);

                        HttpResponse(res + result + str9);
//                        if (trfl.equals("yes")) {
//                            String result = obj.getString("类型相关视频");
//
//                            String str9 = msg.getData().getString("SearchData");//接受msg传递过来的参数
//
//                            String ciphertext = obj.getString("地址密文");
//                            String res = Decrypt.RsaDecrypt(VideoPlayerActivity.this, ciphertext);
//
//                            HttpResponse(res + result + str9);
//                            //Log.i("response===========>",SD_searchport()+str9);
//                        } else if (trfl.equals("no")) {
//
//                            String result = obj.getString("UN类型相关视频");
//
//                            String str9 = msg.getData().getString("SearchData");//接受msg传递过来的参数
//
//                            String ciphertext = obj.getString("地址密文");
//                            String res = Decrypt.RsaDecrypt(VideoPlayerActivity.this, ciphertext);
//                            HttpResponse(res + result + str9);
//                            //Log.i("response===========>",SD_searchport()+str9);
//                        } else Log.i("response===========>", "配置文件错误");


                    } catch (Exception e) {

                        Toast.makeText(VideoPlayerActivity.this, "配置文件错误", Toast.LENGTH_SHORT).show();
//异常处理
                    }

                    break;
                case 16:
//                    String jsondata = msg.getData().getString("jsondata");//接受msg传递过来的参数
//                    searchdata.setText(jsondata);

                    SearchVideoData((ArrayList<Related_C>) related_cList);
                    break;

                case 22:
                    click_discuss_data((ArrayList<player_discuss_class>) player_discuss_classList);
                    break;


                case 80:
                    //private String vod_score, vod_name, vod_class, vod_pic, vod_play_url, vod_add_time,vod_value_add;
                    String downvod_score = msg.getData().getString("vod_score");//接受msg传递过来的参数
                    String downvod_name = msg.getData().getString("vod_name");//接受msg传递过来的参数
                    String downvod_class = msg.getData().getString("vod_class");//接受msg传递过来的参数
                    String downvod_pic = msg.getData().getString("vod_pic");//接受msg传递过来的参数
                    String downvod_play_url = msg.getData().getString("vod_play_url");//接受msg传递过来的参数
                    String downvod_add_time = msg.getData().getString("vod_add_time");//接受msg传递过来的参数
                    String downvod_value_add = msg.getData().getString("vod_value_add");//接受msg传递过来的参数


                    db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
                    //使用 ContentValues 来对要添加的数据进行组装
                    ContentValues valuedown = new ContentValues();
                    // 开始组装第一条数据
                    valuedown.put("vod_score", downvod_score);
                    valuedown.put("vod_name", downvod_name);
                    valuedown.put("vod_class", downvod_class);
                    valuedown.put("vod_pic", downvod_pic);
                    valuedown.put("vod_play_url", downvod_play_url);
                    valuedown.put("vod_add_time", downvod_add_time);
                    valuedown.put("vod_value_add", downvod_value_add);
                    // 插入第一条数据love_
                    db.insert("downTable", null, valuedown);
                    valuedown.clear();
                    db.close();


//                    //在owldatabase新建一个文件
//                    //判断是否存在下载的文件
//                    if (!FileoOperations.fileIsExists(filePath + "VideoDownload" + ".txt")) {
//
//                        //不存在就说明是第一个，组合成json
//                        String content = "[{\n" +
//                                "\t\"vod_score\": \"" + downvod_score + "\",\n" +
//                                "\t\"vod_name\": \"" + downvod_name + "\",\n" +
//                                "\t\"vod_class\": \"" + downvod_class + "\",\n" +
//                                "\t\"vod_value_add\": \"" + downvod_value_add + "\",\n" +
//                                "\t\"vod_add_time\": \"" + downvod_add_time + "\",\n" +
//                                "\t\"vod_pic\": \"" + downvod_pic + "\",\n" +
//                                "\t\"vod_play_url\": \"" + downvod_play_url + "\"\n" +
//                                "}]";
//                        //不存在就创建
//                        FileoOperations.writeData(filePath, "VideoDownload", content);
//
//
//                    } else {
//
//                        String content = ",{\n" +
//                                "\t\"vod_score\": \"" + downvod_score + "\",\n" +
//                                "\t\"vod_name\": \"" + downvod_name + "\",\n" +
//                                "\t\"vod_class\": \"" + downvod_class + "\",\n" +
//                                "\t\"vod_value_add\": \"" + downvod_value_add + "\",\n" +
//                                "\t\"vod_add_time\": \"" + downvod_add_time + "\",\n" +
//                                "\t\"vod_pic\": \"" + downvod_pic + "\",\n" +
//                                "\t\"vod_play_url\": \"" + downvod_play_url + "\"\n" +
//                                "}]";
//                        //读取里面的所有数据
//
//                        String FileContent = FileoOperations.readFromSDFile(VideoPlayerActivity.this, filedown);
//
//
//                        FileoOperations.writeAssignTxt(filedown, FileContent.replace("]", content).trim());
//                    }

                    break;

            }
        }
    };


    private Bitmap bm;

    /* 将图片抓下来预览或并设置为桌面的方法 */
    private void setImage(String path) {
        try {
            URL url = new URL(path);
            URLConnection conn = url.openConnection();
            conn.connect();

            /* 设置为桌面 */
            VideoPlayerActivity.this.setWallpaper(conn.getInputStream());
            bm = null;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private Related_C relatedC;

    private void HttpResponse(String url) {

        related_cList.clear();

        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String res = response.body().string();
//               // Log.i("onResponse===========>",res);
//                Message msg = new Message();
//                msg.what = 16;
//                Bundle bundle = new Bundle();
//                bundle.putString("jsondata",res);  //往Bundle中存放数据
//                // bundle.putString("text2","Time：2016-11-03");  //往Bundle中put数据
//                msg.setData(bundle);//mes利用Bundle传递数据
//                handler.sendMessage(msg);//用activity中的handler发送消息

                List<Related_C> collectionStationCList = JSON.parseArray(res, Related_C.class);
                for (Related_C normVideo : collectionStationCList) {
                    relatedC = new Related_C();

//    vod_score  ---评分
//    vod_name	----影片名称
//    vod_class  ----类型
//    vod_pic ----图片地址
//    vod_play_url --视频地址
//    vod_add_time  ---添加日期

//    vod_actor ---演员
//    vod_director ---导演
//    vod_blurb  ---影片简介
//    vod_area  ---地区
//    vod_year  ---上映年份
//    vod_lang  ---语言

                    String vod_score = normVideo.getVod_score();
                    String vod_name = normVideo.getVod_name();
                    String vod_class = normVideo.getVod_class();
                    String vod_add_time = normVideo.getVod_add_time();
                    String vod_pic = normVideo.getVod_pic();
                    String vod_play_url = normVideo.getVod_play_url();

                    String vod_actor = normVideo.getVod_actor();
                    String vod_director = normVideo.getVod_director();
                    String vod_blurb = normVideo.getVod_blurb();
                    String vod_area = normVideo.getVod_area();
                    String vod_year = normVideo.getVod_year();
                    String vod_lang = normVideo.getVod_lang();
                    String vod_id = normVideo.getVod_id();

                    // Log.d("ImageviewHolder", "显示图片url======" + vod_pic);

                    relatedC.setVod_score("评分:" + vod_score);
                    relatedC.setVod_name(vod_name);
                    relatedC.setVod_class(vod_class + "#" + vod_year + "#" + vod_area + "#" + vod_lang + "#" + vod_id);
                    relatedC.setVod_add_time(vod_add_time);
                    relatedC.setVod_pic(vod_pic);
                    relatedC.setVod_pic_url(vod_pic);
                    relatedC.setVod_play_url(vod_play_url);
                    relatedC.setVod_value_add("导演：" + vod_director + "\n演员：" + vod_actor + "\n类型：" + vod_class + "\n上映地区：" + vod_area + "\n上映年份：" + vod_year + "\n语言：" + vod_lang + "\n$片名：" + vod_name + "\n剧情简介：" + vod_blurb);


                    related_cList.add(relatedC);


                }
                Message msg = new Message();
                msg.what = 16;
                handler.sendMessage(msg);//用activity中的handler发送消息
            }
        });

    }

    private Related_A relatedA;

    public void SearchVideoData(ArrayList<Related_C> related_cList) {


        relatedA = new Related_A(R.layout.related_item, this, related_cList);

        lv_related.setAdapter(relatedA);
        lv_related.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                //跳转提示
                //Toast.makeText(SearchCinemaActivity.this, "Click item" + i, Toast.LENGTH_SHORT).show();
                final TextView vod_class1 = (TextView) view.findViewById(R.id.vod_class);
                final TextView vod_score1 = (TextView) view.findViewById(R.id.vod_score);
                final TextView vod_name1 = (TextView) view.findViewById(R.id.vod_name);
                final TextView vod_add_time1 = (TextView) view.findViewById(R.id.vod_add_time);
                final TextView vod_play_url1 = (TextView) view.findViewById(R.id.vod_play_url);
                final TextView vod_pic_url1 = (TextView) view.findViewById(R.id.vod_pic_url);
                final TextView vod_value_add1 = (TextView) view.findViewById(R.id.vod_value_add);


                String vod_class2 = vod_class1.getText().toString();
                String vod_score2 = vod_score1.getText().toString();
                String vod_name2 = vod_name1.getText().toString();
                String vod_add_time2 = vod_add_time1.getText().toString();
                String vod_play_url2 = vod_play_url1.getText().toString();
                String vod_pic_url2 = vod_pic_url1.getText().toString();
                String vod_value_add2 = vod_value_add1.getText().toString();


                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("vod_class", vod_class2);
                bundle.putString("vod_score", vod_score2);
                bundle.putString("vod_name", vod_name2);
                bundle.putString("vod_pic", vod_pic_url2);
                bundle.putString("vod_add_time", vod_add_time2);
                bundle.putString("vod_play_url", vod_play_url2);
                bundle.putString("vod_value_add", vod_value_add2);
                intent.putExtras(bundle);
                intent.setClass(VideoPlayerActivity.this, VideoPlayerActivity.class);
                startActivity(intent);

            }
        });


    }








    /*下载视频                                  --------------------------------------*/

    private void onDownload() {

        //新建一个File，传入文件夹目录
        File file = new File("/storage/emulated/0/OwlDatabase/video");
//判断文件夹是否存在，如果不存在就创建，否则不创建
        if (!file.exists()) {
            //通过file的mkdirs()方法创建目录中包含却不存在的文件夹
            file.mkdirs();
        }


        dirPath = "/storage/emulated/0/OwlDatabase/video";

        Log.i("dirPath---------------", dirPath);
        M3U8DownloaderConfig
                .build(getApplicationContext())
                .setSaveDir(dirPath)
        ;

        initDownloadlistin();


    }


    private void initDownloadlistin() {
        Intent intent = getIntent();

        M3U8Task bean0 = new M3U8Task(seturl_split_av(intent.getStringExtra("vod_play_url")));
        taskList[0] = bean0;

        //M3U8Task mediaBean = taskList[0];
        down_info.setText("建立连接中..");

        M3U8Downloader.getInstance().setOnM3U8DownloadListener(onM3U8DownloadListener);


        //file:////storage/emulated/0/Android/data/com.shuchuwenku.cloudstood/cache/DownloadMovie/d41d8cd98f00b204e9800998ecf8427e/local.m3u8


        String url = bean0.getUrl();
        if (M3U8Downloader.getInstance().checkM3U8IsExist(url)) {
            //清空
            down_info.setText("已缓存");
        } else {
            M3U8Downloader.getInstance().download(url);
        }

    }


    private String seturl_split_av(String full_url) {

        //搜索是否存在# 存在就遍历
        //不存在就安按照$取数

        //拆分 full_url = purl

        boolean status = full_url.contains("$");
        if (status) {
            System.out.println("存在");
//            //拆分
//            String[] temp;
//            String delimeter = "在线播放$";  // 指定分割字符

//            StringUtils stringutils =  new com.shuchuwenku.cloudstood.StringUtils();
//            full_url=stringutils.substringBefore(full_url,"$");
            //temp = full_url.split(delimeter); // 分割字符串

            //full_url=full_url.substring(full_url.lastIndexOf("$"));
            int one = full_url.lastIndexOf("$");
            full_url = full_url.substring((one + 1), full_url.length());

            return full_url;

        } else {
            System.out.println("不存在");
            //不存在就 按照$拆分成数组，第一[0]就写到控件[1]写到链接
            return full_url;
        }

        //返回----第1集$https:\/\/cn1.download05.com\/hls\/20181113\/c14b3cf7e591cee087a76d2c734a0576\/1542111690\/index.m3u8
        //或者  ----HD高清$https:\/\/cn2.5311444.com\/hls\/20181028\/a81ad1d754f4af6ad6344da89fe3c0ae\/1540700636\/index.m3u8
        //return null;
    }

    private OnM3U8DownloadListener onM3U8DownloadListener = new OnM3U8DownloadListener() {


        @Override
        public void onDownloadSuccess(M3U8Task task) {
            super.onDownloadSuccess(task);
            taskList[0] = task;
            //Log.i("onDownloadSuccess", "onDownloadSuccess");
            down_info.setText("缓存完成");
            progressBarView.setVisibility(View.GONE);


//private String vod_score, vod_name, vod_class, vod_pic, vod_play_url, vod_add_time,vod_value_add;


            String url = taskList[0].getUrl();
            String FILE_ADDRESS = M3U8Downloader.getInstance().getM3U8Path(url);//文件地址---d41d8cd98f00b204e9800998ecf8427e/local.m3u8  有问题
            //info_player.setText("进度:" + String.format("%.1f ",mediaBean.getProgress() * 100)+ "%|速度:" + mediaBean.getFormatSpeed());
            Log.e("55555555555", "M3U8Downloader.getInstance().getM3U8Path(url)==" + FILE_ADDRESS);
            // FILE_ADDRESS

            String FILE_ADDRESS1 = FILE_ADDRESS.replace("Android/data/cc.booku.owlbox/cache/", "owldatabase/");

            //新页面接收数据
            Bundle bundle = getIntent().getExtras();
            String vod_class = bundle.getString("vod_class");
            String vod_score = bundle.getString("vod_score");
            String vod_name = bundle.getString("vod_name");
            String vod_add_time = bundle.getString("vod_add_time");
            String vod_play_url = bundle.getString("vod_play_url");
            String vod_pic = bundle.getString("vod_pic");
            String vod_value_add = bundle.getString("vod_value_add");

            //将数据存入数据库
            Log.i("vod_pic", "vod_pic====" + vod_pic);
            Message msg = new Message();
            msg.what = 80;
            Bundle bundle2 = new Bundle();
            bundle2.putString("vod_class", vod_class);  //往Bundle中存放数据
            bundle2.putString("vod_score", vod_score);
            bundle2.putString("vod_name", vod_name);
            bundle2.putString("vod_add_time", vod_add_time);
            bundle2.putString("vod_pic", vod_pic);
            bundle2.putString("vod_value_add", vod_value_add);
            bundle2.putString("vod_play_url", "file://" + FILE_ADDRESS1);
            msg.setData(bundle2);//mes利用Bundle传递数据
            handler.sendMessage(msg);//用activity中的handler发送消息


        }


        @Override
        public void onDownloadProgress(final M3U8Task task) {
            super.onDownloadProgress(task);
            notifyChanged(task);
            //Log.i("onDownloadProgress", "onDownloadProgress");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    progressBarhandler.sendEmptyMessage((int) (task.getProgress() * 100));
                    down_info.setText(String.format(task.getFormatSpeed()));
                }
            });

        }

        @Override
        public void onDownloadError(final M3U8Task task, Throwable errorMsg) {
            super.onDownloadError(task, errorMsg);
            notifyChanged(task);
            //Log.i("onDownloadError", "onDownloadError");
            down_info.setText("缓存失败");
        }

    };

    private void notifyChanged(final M3U8Task task) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                taskList[0] = task;
                //notifyDataSetChanged();
            }
        });

    }


    final Handler progressBarhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            progressBarView.setProgress(msg.what);
        }
    };


    //
//
    private void ImageDialog(String picStr) {
        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_ad)
                .setScreenHeightAspect(this, 0.7f)
                .setScreenWidthAspect(this, 0.9f)
                .setCancelableOutside(false)
                .setOnBindViewListener(new OnBindViewListener() {
                    @Override
                    public void bindView(BindViewHolder viewHolder) {
                        //可对图片进行修改
                        NetworkImageView iv_icon = viewHolder.getView(R.id.iv_icon);
                        iv_icon.setImageURL(picStr);
                    }
                })
                .addOnClickListener(R.id.iv_close)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        tDialog.dismiss();
                    }
                })
                .create()
                .show();
    }

//***********************************************************************************************************

    public void click_discuss_data(ArrayList<player_discuss_class> player_discuss_classList) {


        player_discuss_AdapterA = new player_discuss_Adapter(R.layout.player_discuss_item, this, player_discuss_classList);

        player_discuss_list.setAdapter(player_discuss_AdapterA);
        player_discuss_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {


//                final TextView comment_name = (TextView) view.findViewById(R.id.player_discuss_comment_nameid);
//                final TextView comment_time = (TextView) view.findViewById(R.id.player_discuss_comment_timeid);
//                final TextView comment_content = (TextView) view.findViewById(R.id.player_discuss_comment_contentid);
//                final TextView comment_value = (TextView) view.findViewById(R.id.player_discuss_comment_valueid);
//
//
//
//                final String comment_names = comment_name.getText().toString();
//                final String comment_times = comment_time.getText().toString();
//                final String comment_contents = comment_content.getText().toString();
//                String comment_values = comment_value.getText().toString();


            }
        });


        player_discuss_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, final View view,
                                           final int i, long l) {
//                final TextView comment_value = (TextView) view.findViewById(R.id.player_discuss_comment_valueid);
//                String comment_values = comment_value.getText().toString();
//                final TextView comment_name = (TextView) view.findViewById(R.id.player_discuss_comment_nameid);
//                final String[] valusedata = comment_values.split("\\#");
//                pulldownlist(valusedata[0], comment_name.getText().toString());
                return true;
            }
        });

    }


    private player_discuss_Adapter player_discuss_AdapterA;
    public player_discuss_class discuss_classC;

    public void init_discuss_data(String Surl_file) {

        player_discuss_classList.clear();

        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request.Builder requestBuilder = new Request.Builder().url(Surl_file);
        //可以省略，默认是GET请求
        requestBuilder.method("GET", null);
        Request request = requestBuilder.build();
        Call mcall = mOkHttpClient.newCall(request);
        mcall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("1111", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsoninfo = response.body().string();
                ByteArrayInputStream stream = new ByteArrayInputStream(jsoninfo.getBytes());
                StringBuffer stringBuffer = new StringBuffer();
                String str = null;
                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
                //03.使用fastJson解析Json、


                List<player_discuss_class> discussc = JSON.parseArray(stringBuffer.toString(), player_discuss_class.class);
                for (player_discuss_class vpv : discussc) {
                    discuss_classC = new player_discuss_class();


                    String comment_id = vpv.getComment_id();
                    String comment_rid = vpv.getComment_rid();
                    String user_id = vpv.getUser_id();
                    String comment_name = vpv.getComment_name();
                    String comment_content = vpv.getComment_content();
                    String comment_time = vpv.getComment_time();
                    String comment_status = vpv.getComment_status();


//                    discuss_classC.setComment_id(comment_id);
//                    discuss_classC.setComment_rid(comment_rid);
//                    discuss_classC.setUser_id(user_id);
                    discuss_classC.setComment_name(comment_name);
                    discuss_classC.setComment_content(comment_content);
                    discuss_classC.setComment_time(comment_time);
                    discuss_classC.setComment_value(comment_id + "#" + comment_rid + "#" + user_id + "#" + comment_status);

                    player_discuss_classList.add(discuss_classC);
                }
                Message msg = new Message();
                msg.what = 22;
                handler.sendMessage(msg);//用activity中的handler发送消息

            }
        });

    }


//测试网址是否可用
//    public static Boolean checkUrl2(String address,int timeout)
//    {
//        Socket socket = null;
//        try {
//            URL url = new URL(address);
//            String host = url.getHost();
//            int port = url.getPort();
//            if (port == -1) {
//                port = 80;
//            }
//            socket = new Socket();
//            InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName(host), port);
//
//            socket.connect(isa, timeout);
//            if (socket.isConnected()) {
//                return true;
//            } else {
//                return false;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return false;
//        } finally {
//            if (socket != null) {
//                try {
//                    socket.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }

//*****************************************************************IJKPLAYER*********************************

    private OnVideoViewStateChangeListener mOnVideoViewStateChangeListener = new OnVideoViewStateChangeListener() {
        @Override
        public void onPlayerStateChanged(int playerState) {
            switch (playerState) {
                case IjkVideoView.PLAYER_NORMAL://小屏
                    break;
                case IjkVideoView.PLAYER_FULL_SCREEN://全屏
                    break;
            }
        }

        @Override
        public void onPlayStateChanged(int playState) {
            switch (playState) {
                case IjkVideoView.STATE_IDLE:
                    break;
                case IjkVideoView.STATE_PREPARING:
                    break;
                case IjkVideoView.STATE_PREPARED:
                    //需在此时获取视频宽高
                    int[] videoSize = ijkVideoView.getVideoSize();
                    L.d("视频宽：" + videoSize[0]);
                    L.d("视频高：" + videoSize[1]);
                    break;
                case IjkVideoView.STATE_PLAYING:
                    break;
                case IjkVideoView.STATE_PAUSED:
                    break;
                case IjkVideoView.STATE_BUFFERING:
                    break;
                case IjkVideoView.STATE_BUFFERED:
                    break;
                case IjkVideoView.STATE_PLAYBACK_COMPLETED:
                    break;
                case IjkVideoView.STATE_ERROR:
                    break;
            }
        }
    };

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

//    @Override
//    protected void onPause() {
//        super.onPause();
//        ijkVideoView.pause();
//    }
//
//    @Override
//    protected void onResume() {
//        super.onResume();
//        ijkVideoView.resume();
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        init_ijkplayer(tv_url, tv_series);
//        ijkVideoView.release();
//    }
//
//
//    @Override
//    public void onBackPressed() {
//        if (!ijkVideoView.onBackPressed()) {
//            super.onBackPressed();
//        }
//    }


    @Override
    protected void onPause() {
        super.onPause();
        ijkVideoView.pause();
        //暂停
    }

    @Override
    protected void onResume() {
        super.onResume();
        ijkVideoView.resume();
        //继续
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        init_ijkplayer(tv_url, tv_series);
        ijkVideoView.release();

        //发布
    }


    @Override
    public void onBackPressed() {
//        if (!ijkVideoView.onBackPressed()) {
//            //finish();
//            super.onBackPressed();
//            //NavUtils.navigateUpTo(this, new Intent(this, MainoldActivity.class));
//            //finish();
//        }
        finish();
    }


    int i = 0;

    public void setMirrorRotate(View view) {
        ijkVideoView.setMirrorRotation(i % 2 == 0);
        i++;
    }


    private void funlove_init() {


        //收藏初始化
        Bundle bundle = getIntent().getExtras();
        String vod_name = bundle.getString("vod_name");
        db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
        Cursor cursor = db.rawQuery("select vod_name from loveTable where vod_name = vod_name ", null);
        while (cursor.moveToNext()) {
            //遍历出表名
            String title_str = cursor.getString(0);
            if (title_str.equals(vod_name)) {
                //love_state = true;//已经收藏
                //  love_img.setImageResource(R.drawable.ic_love_yes);

                love_collect.setText("已收藏");
                //Log.i("System.out------", "love_state=false");
            }
            // Log.i("System.out", title_str);
        }
    }

    private void fundown_init() {


        //收藏初始化
        Bundle bundle = getIntent().getExtras();
        String vod_name = bundle.getString("vod_name");
        db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
        Cursor cursor = db.rawQuery("select vod_name from downTable where vod_name = vod_name ", null);
        while (cursor.moveToNext()) {
            //遍历出表名
            String title_str = cursor.getString(0);
            if (title_str.equals(vod_name)) {
                down_info.setText("已下载");
            }
        }
    }

    private boolean funhistory_init() {

        boolean state = false;
        //历史初始化
        Bundle bundle = getIntent().getExtras();
        String vod_name = bundle.getString("vod_name");
        db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
        Cursor cursor = db.rawQuery("select vod_name from collectTable where vod_name = vod_name ", null);
        while (cursor.moveToNext()) {
            //遍历出表名
            String title_str = cursor.getString(0);
            if (title_str.equals(vod_name)) {

                state = true;

            } else {
                state = false;
            }
            // Log.i("System.out", title_str);
        }

        return state;
    }

    private void funhistory() {


        if (funhistory_init()) {
            Log.i("System.out------", "已经存在不添加");
        } else {


            //新页面接收数据
            Bundle bundle = getIntent().getExtras();
            String vod_class = bundle.getString("vod_class");
            String vod_score = bundle.getString("vod_score");
            String vod_name = bundle.getString("vod_name");
            String vod_add_time = bundle.getString("vod_add_time");
            String vod_play_url = bundle.getString("vod_play_url");
            String vod_pic = bundle.getString("vod_pic");
            String vod_value_add = bundle.getString("vod_value_add");

            db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
            //使用 ContentValues 来对要添加的数据进行组装
            ContentValues valuec = new ContentValues();
            // 开始组装第一条数据
            valuec.put("vod_score", vod_score);
            valuec.put("vod_name", vod_name);
            valuec.put("vod_class", vod_class);
            valuec.put("vod_pic", vod_pic);
            valuec.put("vod_play_url", vod_play_url);
            valuec.put("vod_add_time", vod_add_time);
            valuec.put("vod_value_add", vod_value_add);
            // 插入第一条数据love_
            db.insert("collectTable", null, valuec);
            valuec.clear();
            db.close();

            // love_collect.setText("已收藏");
        }

    }

}
